import React, { useState, useRef, useCallback, useEffect, useMemo, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { debounce } from 'lodash';
import { DndProvider, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Modal, ConfigProvider, App, message, Input, Button } from 'antd';
import { FixedSizeGrid } from 'react-window';
import 'animate.css';

import Header from '../../components/header/header';
import ImageCard from '../../components/ImageCard/ImageCard';
import {
    getCanvasList,
    createCanvas,
    deleteCanvas,
    getShareCode,
    unshareCanvas,
    joinCollaboration,
    leaveCollaboration
} from '../../api/canvas'; // 导入API函数
import './home.css';

// 创建画布组件
const CanvasDropArea = ({ children, onDrop }) => {
    const canvasRef = useRef(null);
    const dropRequestRef = useRef(null);

    const [, drop] = useDrop(
        () => ({
            accept: 'image',
            drop: (item, monitor) => {
                // 获取鼠标位置
                const clientOffset = monitor.getClientOffset();
                if (!clientOffset || !canvasRef.current) return;

                // 获取画布元素的位置和滚动偏移
                const canvasRect = canvasRef.current.getBoundingClientRect();
                const scrollLeft = canvasRef.current.scrollLeft;
                const scrollTop = canvasRef.current.scrollTop;

                // 计算鼠标相对于画布的位置，考虑滚动
                const x = clientOffset.x - canvasRect.left + scrollLeft;
                const y = clientOffset.y - canvasRect.top + scrollTop;

                // 调整位置，考虑卡片的尺寸
                const newPosition = {
                    x: Math.max(0, x - 100), // 卡片宽度为200px的一半
                    y: Math.max(0, y - 75) // 卡片高度为150px的一半
                };

                // 使用rAF更新位置，避免在拖拽期间造成性能问题
                cancelAnimationFrame(dropRequestRef.current);
                dropRequestRef.current = requestAnimationFrame(() => {
                    // 更新卡片位置
                    onDrop(item.id, newPosition);
                });

                return undefined;
            }
        }),
        [onDrop]
    );

    // 组合引用
    drop(canvasRef);

    return (
        <div ref={canvasRef} className="canvas">
            {children}
        </div>
    );
};

// 卡片项组件
const CardItem = memo(({ data, index, style }) => {
    const { images, onSelect, onDelete, onShare, onCancelShare } = data;
    const image = images[index];

    if (!image) return null;

    return (
        <div style={style}>
            <ImageCard
                key={image.id}
                {...image}
                isOwner={image.isOwner}
                onSelect={onSelect}
                onDelete={onDelete}
                onShare={onShare}
                onCancelShare={onCancelShare}
            />
        </div>
    );
});

const STORAGE_KEY = 'canvas_images';

const Home = () => {
    // 添加选中画布状态
    const [selectedCanvas, setSelectedCanvas] = useState(null);
    // 添加画布编辑状态
    const [isEditing, setIsEditing] = useState(true);

    // 添加邀请码状态
    const [inviteCode, setInviteCode] = useState('');

    // 监听导出和导入事件
    useEffect(() => {
        const handleExportSuccess = () => {
            message.success('导出成功');
        };
        const handleExportFail = () => {
            message.error('导出失败');
        };
        const handleImportSuccess = () => {
            message.success('图片导入成功');
        };
        const handleImportFail = () => {
            message.error('图片导入失败');
        };

        document.addEventListener('export-success', handleExportSuccess);
        document.addEventListener('export-fail', handleExportFail);
        document.addEventListener('import-success', handleImportSuccess);
        document.addEventListener('import-fail', handleImportFail);

        return () => {
            document.removeEventListener('export-success', handleExportSuccess);
            document.removeEventListener('export-fail', handleExportFail);
            document.removeEventListener('import-success', handleImportSuccess);
            document.removeEventListener('import-fail', handleImportFail);
        };
    }, []);

    // 初始化空画布数组，通过API获取数据
    const [images, setImages] = useState([]);
    const [allImages, setAllImages] = useState([]);
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 虚拟列表容器尺寸
    const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
    const containerRef = useRef(null);
    // 添加一个ref来追踪是否已经发起过请求
    const hasInitialFetch = useRef(false);

    // 监听容器尺寸变化
    useEffect(() => {
        const updateSize = () => {
            if (containerRef.current) {
                // 使用 requestAnimationFrame 延迟读取布局信息
                requestAnimationFrame(() => {
                    requestAnimationFrame(() => {
                        setContainerSize({
                            width: containerRef.current.offsetWidth,
                            height: containerRef.current.offsetHeight
                        });
                    });
                });
            }
        };

        // 初始化时更新尺寸
        updateSize();

        // 使用 ResizeObserver 监听容器尺寸变化
        const resizeObserver = new ResizeObserver(updateSize);

        if (containerRef.current) {
            resizeObserver.observe(containerRef.current);
        }

        // 清理函数
        return () => {
            if (containerRef.current) {
                resizeObserver.unobserve(containerRef.current);
            }
        };
    }, []); //

    // 从API获取画布列表的函数
    const fetchCanvasList = useCallback(async () => {
        // 如果已经在加载中，不要重复请求
        if (loading) return;

        try {
            setLoading(true);
            // 检查是否登录
            const token = localStorage.getItem('token');
            console.log('fetchCanvasList检查token:', token);

            if (!token) {
                console.log('用户未登录，无法获取画布列表');
                setImages([]);
                return;
            }

            // 已登录，调用API获取画布列表
            const response = await getCanvasList();
            console.log('画布列表响应:', response);

            if (response && response.success && response.data) {
                const canvasList = response.data.map((canvas) => {
                    return {
                        id: canvas._id,
                        imageUrl: canvas.thumbnail || canvas.img || '/封面.jpg',
                        title: canvas.title || `画布${canvas._id}`,
                        isOwner: canvas.isOwner,
                        position: { x: 0, y: 0 },
                        sharedCode: canvas.shareCode?.code || '',
                        isShared: canvas.shareCode ? true : false
                    };
                });

                console.log(`获取到${canvasList.length}个画布`);
                setImages(canvasList);

                setAllImages(canvasList);
            }
        } catch (error) {
            console.error('获取画布列表失败:', error);
            message.error('获取画布列表失败');
        } finally {
            setLoading(false);
        }
    }, [loading]);

    // 监听用户登录事件和页面加载
    useEffect(() => {
        // 检查是否已登录且是否已经发起过初始请求
        const token = localStorage.getItem('token');
        if (token && !hasInitialFetch.current) {
            hasInitialFetch.current = true;
            fetchCanvasList();
        }

        // 监听用户登录事件
        const handleUserLogin = (event) => {
            console.log('用户登录事件触发，获取画布列表', event.detail);
            // const newToken = event.detail.token;
            if (
                /* newToken 
              && ! */
                localStorage.getItem('token')
            ) {
                // 登录请求中已经存储了token,不用重复存储
                // console.log('从登录事件中获取token:', newToken);
                // localStorage.setItem('token', newToken);

                // 重置hasInitialFetch，因为这是新的登录
                hasInitialFetch.current = false;
                fetchCanvasList();
            }
        };

        // 监听用户登出事件
        const handleUserLogout = () => {
            console.log('用户登出事件触发，清空画布列表');
            setImages([]);
            // 重置hasInitialFetch，因为用户已登出
            hasInitialFetch.current = false;
        };

        // 添加事件监听
        document.addEventListener('user-login', handleUserLogin);
        document.addEventListener('user-logout', handleUserLogout);

        // 组件卸载时移除事件监听
        return () => {
            document.removeEventListener('user-login', handleUserLogin);
            document.removeEventListener('user-logout', handleUserLogout);
        };
    }, [fetchCanvasList]);

    // 创建一个虚拟列表模式标志
    const [isVirtualMode] = useState(true);

    const debouncedUpdate = useMemo(() => {
        // 在虚拟列表模式下，此函数不再有实际作用
        if (isVirtualMode) {
            return () => {}; // 返回空函数
        }

        const debouncedFn = debounce((id, newPosition) => {
            setImages((prevImages) => {
                const newImages = prevImages.map((img) =>
                    img.id === id ? { ...img, position: newPosition } : img
                );
                return newImages;
            });
        }, 16);

        return debouncedFn;
    }, [isVirtualMode]);

    useEffect(() => {
        return () => {
            if (debouncedUpdate.cancel) {
                debouncedUpdate.cancel();
            }
        };
    }, [debouncedUpdate]);

    const handleDrop = useCallback(
        (id, newPosition) => {
            // 在虚拟列表模式下，不处理拖拽
            if (isVirtualMode) return;

            debouncedUpdate(id, newPosition);
        },
        [debouncedUpdate, isVirtualMode]
    );

    // 处理画布选择
    const navigate = useNavigate();

    const handleSelectCanvas = useCallback(
        (id) => {
            setSelectedCanvas(id);
            // 查找对应画布对象
            const selectedImage = images.find((img) => img.id === id);
            // 通过路由状态传递标题
            navigate(`/canvas/${id}`, {
                state: {
                    title: selectedImage ? selectedImage.title : `画布${id}`
                }
            });
        },
        [navigate, images]
    );
    useEffect(() => {
        // 状态更新后的逻辑
        //  alert(images.length)
    }, [images]);
    // 添加新画布
    const handleAddCanvas = useCallback(async () => {
        // 检查是否有 token
        const token = localStorage.getItem('token');
        if (!token) {
            message.warning('请先登录');
            return;
        }

        try {
            const username = localStorage.getItem('username');

            // 先更新状态来记录正在添加的画布数量
            setImages((prevImages) => {
                const newImages = [
                    ...prevImages,
                    {
                        id: `pending-${Date.now()}`,
                        isPending: true,
                        position: { x: 0, y: 0 } // 位置不再重要，由虚拟列表控制
                    }
                ];
                // 获取新增后的数量（不包括 pending 状态的画布）
                const actualCount = newImages.filter((img) => !img.isPending).length;
                const canvasTitle = `${username}的画布${actualCount + 1}`;

                // 调用API创建画布
                createCanvas(
                    canvasTitle,
                    '' // 不设置初始封面图片
                )
                    .then((response) => {
                        if (response && response.code === 200 && response.data) {
                            // 使用API返回的画布数据
                            const newCanvasId = response.data;

                            // 构建画布对象
                            const canvasObj = {
                                id: newCanvasId,
                                imageUrl: '', // 不设置初始封面图片
                                title: canvasTitle,
                                isOwner: true,
                                position: { x: 0, y: 0 },
                                isNew: true,
                                animation: 'animate__animated animate__zoomIn',
                                isShared: false,
                                sharedCode: ''
                            };

                            // 更新状态 - 添加新画布并移除临时占位画布
                            setImages((prev) => [
                                ...prev.filter((img) => !img.isPending),
                                canvasObj
                            ]);
                            setAllImages((prev) => [...prev, canvasObj]);
                            // 动画结束后移除标记
                            setTimeout(() => {
                                setImages((prev) =>
                                    prev.map((img) =>
                                        img.id === canvasObj.id
                                            ? { ...img, isNew: false, animation: '' }
                                            : img
                                    )
                                );
                            }, 1000);
                        } else {
                            // 移除临时占位画布
                            setImages((prev) => prev.filter((img) => !img.isPending));
                            message.error(response?.msg || '创建画布失败');
                        }
                    })
                    .catch((error) => {
                        // 移除临时占位画布
                        setImages((prev) => prev.filter((img) => !img.isPending));
                        console.error('创建画布出错:', error);
                        message.error('创建画布失败');
                    });

                return newImages;
            });
        } catch (error) {
            console.error('创建画布出错:', error);
            message.error('创建画布失败');
        }
    }, []);

    // 修改画布标题
    const handleTitleChange = useCallback(
        (newTitle) => {
            if (selectedCanvas) {
                setImages((prevImages) => {
                    const newImages = prevImages.map((img) =>
                        img.id === selectedCanvas ? { ...img, title: newTitle || '' } : img
                    );
                    return newImages;
                });
            }
        },
        [selectedCanvas]
    );

    // 获取当前选中画布的标题
    const getCurrentCanvasTitle = useCallback(() => {
        if (!selectedCanvas) return '';
        const selectedImage = images.find((img) => img.id === selectedCanvas);
        return selectedImage ? selectedImage.title : '';
    }, [selectedCanvas, images]);

    // 处理邀请码输入变化
    const handleInviteCodeChange = (e) => {
        setInviteCode(e.target.value);
    };

    // 处理邀请码提交
    const handleInviteCodeSubmit = async () => {
        if (!inviteCode.trim()) {
            message.warning('请输入邀请码');
            return;
        }

        try {
            // 检查用户是否登录
            const token = localStorage.getItem('token');
            if (!token) {
                message.warning('请先登录');
                navigate('/');
                return;
            }

            const response = await joinCollaboration(inviteCode);
            console.log('加入协作响应:', response);

            if (response && response.success) {
                message.success(response.msg || '成功加入协作');
                setInviteCode('');
                // 刷新画布列表
                await fetchCanvasList();
            } else {
                message.error(response?.msg || '加入协作失败');
            }
        } catch (error) {
            console.error('加入协作失败:', error);
            message.error(error.message || '加入协作失败');
        }
    };

    // 处理删除画布
    const handleDeleteCanvas = async (canvas) => {
        try {
            if (!canvas || !canvas.id) {
                message.error('无效的画布信息');
                return;
            }

            // 检查用户是否登录
            const token = localStorage.getItem('token');
            if (!token) {
                message.warning('请先登录');

                return;
            }

            let response;
            if (canvas.isOwner) {
                response = await deleteCanvas(canvas.id);
            } else {
                response = await leaveCollaboration(canvas.id);
            }

            if (response && response.success) {
                // 刷新画布列表
                await fetchCanvasList();
            } else {
                message.error(response?.msg || '操作失败');
            }
        } catch (error) {
            console.error('操作失败:', error);
            message.error(error.response?.data?.msg || error.message || '操作失败');
        }
    };

    // 处理分享功能
    const handleShare = useCallback(
        async (id) => {
            try {
                // 检查用户是否登录
                const token = localStorage.getItem('token');
                if (!token) {
                    message.warning('请先登录');
                    return;
                }

                // 检查画布是否存在
                const canvas = images.find((img) => img.id === id);
                if (!canvas) {
                    message.error('画布不存在');
                    return;
                }

                // 检查是否是画布所有者
                if (!canvas.isOwner) {
                    message.error('只有画布所有者才能生成分享码');
                    return;
                }

                // 设置过期时间为24小时（1440分钟）
                const expireMinutes = 1440;

                // 调用API获取分享码
                const response = await getShareCode(id, expireMinutes);
                console.log('获取分享码响应:', response);

                if (response && response.success && response.data) {
                    const sharedCode = response.data;
                    await navigator.clipboard.writeText(sharedCode);
                    // 更新画布状态，设置分享标志和分享码
                    setImages((prevImages) => {
                        const newImages = prevImages.map((img) =>
                            img.id === id ? { ...img, isShared: true, sharedCode } : img
                        );
                        return newImages;
                    });

                    // 显示分享码
                    Modal.success({
                        title: '分享成功',
                        content: `您的分享码是：${sharedCode}，有效期24小时,分享码已复制到剪贴板`
                    });
                } else {
                    // API返回错误
                    message.error(response?.msg || '获取分享码失败');
                }
            } catch (error) {
                console.error('分享画布失败:', error);
                message.error('分享失败: ' + (error.message || '网络错误'));
            }
        },
        [images]
    );

    // 处理取消分享
    const handleCancelShare = useCallback(async (id) => {
        try {
            // 调用API取消分享
            const response = await unshareCanvas(id);
            console.log('取消分享响应:', response);

            if (response && response.success) {
                // 更新UI状态
                setImages((prevImages) => {
                    const newImages = prevImages.map((img) =>
                        img.id === id ? { ...img, isShared: false, sharedCode: '' } : img
                    );
                    return newImages;
                });

                message.success('已取消分享');
            } else {
                // API返回错误
                message.error(response?.msg || '取消分享失败');
            }
        } catch (error) {
            console.error('取消分享失败:', error);
            message.error('取消分享失败: ' + (error.message || '网络错误'));
        }
    }, []);

    // 卡片布局配置
    const CARD_WIDTH = 220; // 卡片宽度 + 左右间距
    const CARD_HEIGHT = 200; // 卡片高度 + 上下间距

    // 计算虚拟列表的列数
    const columnsCount = Math.max(1, Math.floor(containerSize.width / CARD_WIDTH));

    // 计算网格布局中的行数
    const rowsCount = Math.ceil(images.filter((img) => !img.isPending).length / columnsCount);

    // 添加搜索功能
    const [searchTitle, setSearchTitle] = useState('');

    const handleSearchTitleChange = (e) => {
        setSearchTitle(e.target.value.trim());
        // 使用防抖处理搜索
        handleSearch(e.target.value.trim());
    };

    const handleSearch = (value) => {
        console.log('搜索画布标题:', value);
        console.log('allImages:', allImages);
        if (!value) {
            console.log('搜索画布标题为空');
            setImages(allImages);
        } else {
            const filtered = allImages.filter((img) => img.title.includes(value));
            console.log('搜索结果:', filtered);
            setImages(filtered);
        }
    };

    // 组件卸载时取消防抖
  

    return (
        <ConfigProvider
            wave={{ disabled: true }}
            theme={{
                token: {
                    motion: false
                }
            }}
        >
            <App>
                <div className="home">
                    <Header
                        selectedCanvas={selectedCanvas}
                        canvasTitle={getCurrentCanvasTitle()}
                        onTitleChange={handleSearchTitleChange}
                        isEditing={isEditing}
                    />
                    <div className="content">
                        <div
                            className="add-canvas-button"
                            onClick={handleAddCanvas}
                            title="新增画布"
                        >
                            <div className="plus-icon">+</div>
                        </div>
                        {/* 添加邀请码输入框 */}
                        <div className="invite-code-container">
                            <Input
                                placeholder="请输入邀请码"
                                value={inviteCode}
                                onChange={handleInviteCodeChange}
                                onPressEnter={handleInviteCodeSubmit}
                            />
                            <Button type="primary" onClick={handleInviteCodeSubmit}>
                                提交
                            </Button>
                        </div>

                        <div
                            className="invite-code-container input-search"
                            style={{ top: '100px' }}
                        >
                            <Input
                                placeholder="请输入画布标题"
                                value={searchTitle}
                                onChange={handleSearchTitleChange}
                                // onBlur={handleSearchTitleChange}
                                style={{ width: '255px' }}
                            />
                        </div>

                        <DndProvider
                            backend={HTML5Backend}
                            options={{
                                enableMouseEvents: true,
                                enableTouchEvents: true,
                                enableKeyboardEvents: true,
                                enableHoverOutsideTarget: false,
                                delayTouchStart: 0
                            }}
                        >
                            <CanvasDropArea onDrop={handleDrop}>
                                <div ref={containerRef} className="canvas-grid-container">
                                    {containerSize.width > 0 && (
                                        <FixedSizeGrid
                                            className="canvas-grid"
                                            columnCount={columnsCount}
                                            columnWidth={CARD_WIDTH}
                                            height={containerSize.height}
                                            rowCount={rowsCount}
                                            rowHeight={CARD_HEIGHT}
                                            width={containerSize.width}
                                            overscanRowCount={3} // 预加载更多行
                                            overscanColumnCount={2} // 预加载更多列
                                            itemData={{
                                                images: images.filter((image) => !image.isPending),
                                                onSelect: handleSelectCanvas,
                                                onDelete: handleDeleteCanvas,
                                                onShare: handleShare,
                                                onCancelShare: handleCancelShare
                                            }}
                                        >
                                            {({ columnIndex, rowIndex, style, data }) => {
                                                const index = rowIndex * columnsCount + columnIndex;
                                                const image = data.images[index];

                                                if (!image) return null;

                                                // 调整样式以适应虚拟列表
                                                const adjustedStyle = {
                                                    ...style,
                                                    position: 'absolute',
                                                    padding: '10px'
                                                };

                                                return (
                                                    <div style={adjustedStyle}>
                                                        <ImageCard
                                                            key={image.id}
                                                            {...image}
                                                            position={{ x: 0, y: 0 }} // 重置为相对定位
                                                            useRelativePosition={true} // 添加标志，在ImageCard中处理
                                                            isOwner={image.isOwner}
                                                            onSelect={data.onSelect}
                                                            onDelete={data.onDelete}
                                                            onShare={data.onShare}
                                                            onCancelShare={data.onCancelShare}
                                                        />
                                                    </div>
                                                );
                                            }}
                                        </FixedSizeGrid>
                                    )}
                                </div>
                            </CanvasDropArea>
                        </DndProvider>
                    </div>
                </div>
            </App>
        </ConfigProvider>
    );
};

export default Home;
